﻿using Magicodes.Mvc.AuditFilter;
using Magicodes.Mvc.RoleMenuFilter;
using Magicodes.WeChat.SDK;
using Magicodes.WeiChat.Data.Models;
using Magicodes.WeiChat.Data.Models.CMS;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Ajax;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;

namespace Magicodes.WeiChat.Controllers.WeChat.CMS
{
    public class Article_ManageController : TenantBaseController<WeiChat_KFCInfo>
    {
        [AuditFilter("文章管理列表", "{5AAE6788-3085-4B18-AE79-3E6CD75CB0AD}")]
        [RoleMenuFilter("文章管理", "{5AAE6788-3085-4B18-AE79-3E6CD75CB0AD}", "Admin",
             url: "/Article_Manage", parentId: "{A25A207A-B6DA-470A-B8BC-3BFF5C955666}")]
        // GET: Article_Manage
        public ActionResult Index(string q,int columnId=0, int pageIndex = 1, int pageSize = 10)
        {
            var queryable = db.Article_Manages.AsQueryable();
            if (!string.IsNullOrWhiteSpace(q))
            {
                queryable = queryable.Where(p => p.Title.Contains(q));
            }
            if (columnId != 0)
            {
                queryable = queryable.Where(p => p.ColumnId == columnId);
            }
            var pagedList = new PagedList<Article_Manage>(
                             queryable.OrderByDescending(p => p.CreateTime)
                             .Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(),
                             pageIndex, pageSize, queryable.Count());
            SelectList select = GetSelectList(null);
            ViewBag.select = select;
            return View(pagedList);
        }

        // GET: Column_Manage/Create
        public ActionResult Create(long? id)
        {
            SelectList select = GetSelectList(id);
            ViewBag.select = select;
            return View();
        }

        private SelectList GetSelectList(long? id)
        {
            List<SelectListItem> itemList = new List<SelectListItem>();
            db.Column_Manages.Where(p => p.IsOnePage == false).ToList().ForEach(o =>
            {
                SelectListItem item = new SelectListItem()
                {
                    Value = o.Id.ToString(),
                    Text = o.ColumName,
                    Selected=o.Id==id
                };
                itemList.Add(item);
            });
            SelectList select = new SelectList(itemList, "Value", "Text",id);
            return select;
        }

        // POST: Column_Manage/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public async Task<ActionResult> Create([Bind(Include = "ColumnId,Title,Autor,Content,Intro")] Article_Manage article_Manage)
        {
            if (ModelState.IsValid)
            {
                article_Manage.Release_Time = DateTime.Now;
                SetModel(article_Manage, default(long));
                db.Article_Manages.Add(article_Manage);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View();
        }

        // GET: Column_Manage/Edit
        [HttpGet]
        public ActionResult Edit(long id)
        {
            var af = db.Article_Manages.FirstOrDefault(p => p.Id == id);
            if (af == null)
            {
                ModelState.AddModelError("", "该账号不存在！");
            }
            else
            {                
                var addModel = new Article_Manage()
                {
                    ColumnId = af.ColumnId,
                    Title = af.Title,
                    Autor = af.Autor,
                    Content=af.Content,
                    Intro=af.Intro
                };
                List<SelectListItem> itemList = new List<SelectListItem>();
                db.Column_Manages.ToList().ForEach(o =>
                {
                    SelectListItem item = new SelectListItem()
                    {
                        Value = o.Id.ToString(),
                        Text = o.ColumName,
                        Selected=o.Id==addModel.ColumnId
                    };
                    itemList.Add(item);
                });
                SelectList select = new SelectList(itemList, "Value", "Text");
                ViewBag.select = select;
                return View(addModel);
            }
            return View(new Column_Manage());
        }

        // POST: Site_Article/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(enableValidation: false)]
        public async Task<ActionResult> Edit([Bind(Include = "Id,Content,Title,ColumnId,Autor,Intro")] Article_Manage article_Manage)
        {
            if (ModelState.IsValid)
            {
                Article_Manage articleManage = db.Article_Manages.Find(article_Manage.Id);
                articleManage.Title = article_Manage.Title;
                articleManage.Content = article_Manage.Content;
                articleManage.Autor = article_Manage.Autor;
                articleManage.ColumnId = article_Manage.ColumnId;
                articleManage.Intro = article_Manage.Intro;
                articleManage.UpdateTime = DateTime.Now;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(article_Manage);
        }

        // DELETE: Log_Audit/Delete/5
        [HttpDelete]
        public async Task<ActionResult> Delete(long? id)
        {
            Article_Manage article_Manage = db.Article_Manages.Find(id);
            db.Article_Manages.Remove(article_Manage);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        // POST: Article_Manage/BatchOperation/{operation}
        /// <summary>
        /// 批量操作
        /// </summary>
        /// <param name="operation">操作方法</param>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Article_Manage/BatchOperation/{operation}")]
        public async Task<ActionResult> BatchOperation(string operation, params long[] ids)
        {
            var ajaxResponse = new AjaxResponse();
            if (ids.Length > 0)
            {
                try
                {
                    var models = await db.Article_Manages.Where(p => ids.Contains(p.Id)).ToListAsync();
                    if (models.Count == 0)
                    {
                        ajaxResponse.Success = false;
                        ajaxResponse.Message = "没有找到匹配的项，项已被删除或不存在！";
                        return Json(ajaxResponse);
                    }
                    switch (operation.ToUpper())
                    {
                        case "DELETE":
                            #region 删除
                            {
                                db.Article_Manages.RemoveRange(models);
                                await db.SaveChangesAsync();
                                ajaxResponse.Success = true;
                                ajaxResponse.Message = string.Format("已成功操作{0}项！", models.Count);
                                break;
                            }
                        #endregion
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    ajaxResponse.Success = false;
                    ajaxResponse.Message = ex.Message;
                }
            }
            else
            {
                ajaxResponse.Success = false;
                ajaxResponse.Message = "请至少选择一项！";
            }
            return Json(ajaxResponse);
        }
    }
}